package com.lbyl.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * bitmap工具类,根据指定的网址返回bitmap或null
 *
 * @author libin996@outlook.com
 */

public class DownLoadBitmapUtil {
    private static final String TAG = "DownLoadBitmapUtil";
    /**
     * 根据指定网址获取bitmap,或者null
     *
     * @param urlStr
     * @return
     */
    public static Bitmap downLoadBitmapByUrl(String urlStr) {
        Bitmap bitmap = null;
        if (urlStr == null) {
            return null;
        }
        try {
            Log.i(TAG, "downLoadBitmapByUrl: 即将新建的url是"+urlStr+"嗯");
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() != 200) {
                Log.i(TAG, "downLoadBitmapByUrl: 服务器拒绝访问,状态码是connection.getResponseCode()");
                return null;
            }
            InputStream ins = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(ins);
            ins.close();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }
}
